package services

import (
	"errors"
	"game-server/app/common/request"
	"game-server/app/common/response"
	"game-server/app/models"
	"game-server/global"
)

type vpnService struct{}

var VpnService = new(vpnService)

// CreateVpn 创建VPN
func (s *vpnService) CreateVpn(params request.VpnAddRequest) error {
	var count int64
	global.App.DB.Model(&models.Vpn{}).Where("name = ?", params.Name).Count(&count)
	if count > 0 {
		return errors.New("VPN名称已存在")
	}

	return global.App.DB.Create(&models.Vpn{
		Name:   params.Name,
		Icon:   params.Icon,
		Desc:   params.Desc,
		Link:   params.Link,
		Click:  params.Click,
		Status: params.Status,
		Sort:   params.Sort,
	}).Error
}

// UpdateVpn 更新VPN
func (s *vpnService) UpdateVpn(params request.VpnEditRequest) error {
	var vpn models.Vpn
	if err := global.App.DB.First(&vpn, params.ID).Error; err != nil {
		return errors.New("VPN不存在")
	}

	// 检查名称是否重复
	var count int64
	global.App.DB.Model(&models.Vpn{}).Where("name = ? AND id != ?", params.Name, params.ID).Count(&count)
	if count > 0 {
		return errors.New("VPN名称已存在")
	}

	// 更新信息
	vpn.Name = params.Name
	vpn.Icon = params.Icon
	vpn.Desc = params.Desc
	vpn.Link = params.Link
	vpn.Click = params.Click
	vpn.Status = params.Status
	vpn.Sort = params.Sort

	return global.App.DB.Save(&vpn).Error
}

// DeleteVpn 删除VPN
func (s *vpnService) DeleteVpn(params request.VpnDeleteRequest) error {
	var vpn models.Vpn
	if err := global.App.DB.First(&vpn, params.ID).Error; err != nil {
		return errors.New("VPN不存在")
	}

	return global.App.DB.Delete(&vpn).Error
}

// GetVpn 获取VPN详情
func (s *vpnService) GetVpn(params request.VpnGetRequest) (*models.Vpn, error) {
	var vpn models.Vpn
	if err := global.App.DB.First(&vpn, params.ID).Error; err != nil {
		return nil, errors.New("VPN不存在")
	}
	return &vpn, nil
}

// GetVpnList 获取VPN列表
func (s *vpnService) GetVpnList(params request.VpnListRequest) (response.ListResponse[models.Vpn], error) {
	var res response.ListResponse[models.Vpn]
	var vpns []models.Vpn

	query := global.App.DB.Model(&models.Vpn{})

	// 条件查询
	if params.Name != "" {
		query = query.Where("name LIKE ?", "%"+params.Name+"%")
	}
	if params.Status != nil {
		query = query.Where("status = ?", *params.Status)
	}
	if params.StartTime != "" {
		query = query.Where("created_at >= ?", params.StartTime)
	}
	if params.EndTime != "" {
		query = query.Where("created_at <= ?", params.EndTime)
	}

	// 获取总数
	query.Count(&res.Total)

	// 分页查询
	offset := (params.Page - 1) * params.PageSize
	err := query.Offset(offset).
		Limit(params.PageSize).
		Order("id DESC").
		Find(&vpns).Error

	if err != nil {
		return res, err
	}

	res.List = vpns
	return res, nil
}
